package com.bwie.system.service.impl;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.ProType;
import com.bwie.common.domain.Project;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.ProjectReq;
import com.bwie.common.domain.response.ProTypeResp;
import com.bwie.common.domain.response.ProjectResp;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.system.mapper.ProjectMapper;
import com.bwie.system.service.ProjectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeToLive;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @className: ProjectServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author:
 * @date:
 */
@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageResult<ProjectResp> projectList(ProjectReq projectReq) {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.TOKEN + userKey);
        projectReq.setCreateBy(user.getId());

        PageHelper.startPage(projectReq.getPageNum(), projectReq.getPageSize());
        List<ProjectResp> projectResps = projectMapper.projectList(projectReq);
        List<ProType> proTypes = projectMapper.proTypeListTotal();
        projectResps.forEach(projectResp -> {
            proTypes.forEach(proType -> {
                if(proType.getId().equals(projectResp.getId())){
                    projectResp.setEstimatePriceTotal(proType.getEstimatePriceTotal());
                    projectResp.setVerifyPriceTotal(proType.getVerifyPriceTotal());
                }
            });
        });

        PageInfo<ProjectResp> pageInfo = new PageInfo<>(projectResps);
        PageResult<ProjectResp> result = new PageResult<>(pageInfo.getTotal(), projectResps);

        return result;
    }

    @Override
    public List<ProTypeResp> proTypeList(ProjectReq projectReq) {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.TOKEN + userKey);
        projectReq.setReviewBy(user.getId());
        List<ProTypeResp> proTypes = projectMapper.proTypeList(projectReq);
        return proTypes;
    }

    @Override
    public void addProject(ProjectReq projectReq) {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.TOKEN + userKey);

        //主表添加（需要返回主键id）
        Project project = new Project();
        BeanUtils.copyProperties(projectReq,project);
        project.setStatus(0);
        project.setCreateBy(user.getId());
        project.setCreateTime(new Date());
        //项目名称唯一性略
        projectMapper.addProject(project);
        //中间表填加
        List<ProType> proType = projectReq.getProType();
        projectMapper.addProTypeBatch(project.getId(),proType);

    }

    @Override
    @Transactional
    public void updProject(ProTypeResp proTypeResp) {
        Integer statusProject = 0;//主表状态。默认待提交
        //登录人
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.TOKEN + userKey);

        Project project = new Project();
        project.setId(proTypeResp.getId());

        //审核
        if (user.getRoleId() == 2) {
            //中间表设置审核信息
            proTypeResp.setVerifyBy(user.getId());
            proTypeResp.setVerifyTime(new Date());
            //主表设置审核人信息
            project.setReviewBy(user.getId());
            //获取预估金额和核实金额进行比对
            //预估金额需要从数据库查询，前台信息不可靠
            ProType proType = projectMapper.findByProjectIdAndTypeId(proTypeResp);
            //根据项目id查询项目
            ProjectResp projectResp = projectMapper.selectOneById(proTypeResp);

            BigDecimal estimatePrice = proType.getEstimatePrice();
            BigDecimal verifyPrice = proTypeResp.getVerifyPrice();
            if (estimatePrice.compareTo(verifyPrice) == 0) {
                proTypeResp.setStatus(1);
                statusProject=2;//审核通过
                //rabbitMq发送异步通知结果
                //审核通过时发送消息内容为：“[项目名称]的确认类型[类型名称]估算金额审核通过，确定估算金额：[确认金额]”
                String msg = projectResp.getProjectName()+"的确认类型"+projectResp.getTypeName()+"估算金额审核通过，确定估算金额："+proTypeResp.getVerifyPrice();
                rabbitTemplate.convertAndSend("proType",msg);

            } else {
                proTypeResp.setStatus(2);
                statusProject=3;//审核不通过
                //rabbitMq发送异步通知结果
                //审核不通过时发送消息内容为：“[项目名称]的确认类型[类型名称]金额审核未通过，估算金额：[估算金额]变更为[确定金额]”
                String mag = projectResp.getProjectName()+"的确认类型"+projectResp.getTypeName()+"估算金额审核未通过，估算金额："+proType.getEstimatePrice()+"变更为"+proTypeResp.getVerifyPrice();
                rabbitTemplate.convertAndSend("proType",mag);
            }


        }else{
            statusProject=1;//状态设置为已提交，待审核
        }

        //中间表修改（根据ProjectId和typeId修改）
        projectMapper.updProjectType(proTypeResp);

        project.setStatus(statusProject);
        //主表修改审核状态（projectId和状态）
        projectMapper.updProject(project);

    }
}
